import Taro, {getCurrentPages} from "@tarojs/taro";
import QQMapWX from "./qqmap-wx-jssdk";
import {qqMapKey} from "../service/evn";
import getBaseUrl from "../service/baseUrl";

const base = getBaseUrl();
export const promisify = (func, ctX) => {
  // 返回一个新的function
  return function () {
    // 初始化this作用域
    const ctx = ctX || this;
    // 新方法返回的promise
    return new Promise((resolve, reject) => {
      // 调用原来的非promise方法func，绑定作用域，传参，以及callback（callback为func的最后一个参数）
      func.call(ctx, ...arguments, function () {
        // 将回调函数中的的第一个参数error单独取出
        let args = Array.prototype.map.call(arguments, item => item);
        const err = args.shift();
        // 判断是否有error
        if (err) {
          reject(err);
        } else {
          // 没有error则将后续参数resolve出来
          args = args.length > 1 ? args : args[0];
          resolve(args);
        }
      });
    });
  };
};

export const promiseImage = url => {
  return new Promise(function (resolve) {
    resolve(url);
  });
};
export const isChinese = str => {
  return escape(str).indexOf("%u") >= 0;
};

export const handleName = str => {
  let res = emoj2str(str);
  if (isChinese(res)) {
    res = res.length > 4 ? res.slice(0, 4) + "..." : res;
  } else {
    res = res.length > 7 ? res.slice(0, 7) + "..." : res;
  }
  return res;
};

export const emoj2str = str => {
  return unescape(escape(str).replace(/%uD.{3}/g, ""));
};
/*获取当前页url*/
export const getCurrentPageUrl = () => {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - 1];
  return currentPage.route;
};

export const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join("/") +
    " " +
    [hour, minute, second].map(formatNumber).join(":")
  );
};

export const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};
export const logError = (name, action, info) => {
  if (!info) {
    info = "empty";
  }
  try {
    // eslint-disable-next-line no-undef
    let deviceInfo = wx.getSystemInfoSync();
    var device = JSON.stringify(deviceInfo);
  } catch (e) {
    // eslint-disable-next-line no-undef
    console.error("not support getSystemInfoSync api", err.message);
  }
  let time = formatTime(new Date());
  console.error(time, name, action, info, device);
  if (typeof info === "object") {
    info = JSON.stringify(info);
  }
};

// 拍照/相册
export function getP(count, setImg) {
  Taro.chooseImage({
    count: count || 9,
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera', 'user', 'environment'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
    success: function (res) {
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      const tempFilePaths = res.tempFilePaths;
      setImg(tempFilePaths);
    }
  });
}

export const pageToLogin = () => {
  let path = getCurrentPageUrl();
  Taro.clearStorage()
  if (!path.includes('login')) {
    Taro.reLaunch({
      url: "/pages/login/index"
    });
  }
};

function saveTokenInfo(tokenData) {
  Taro.setStorageSync('access_token', tokenData.access_token);
  Taro.setStorageSync('expires_in', tokenData.expires_in);
  Taro.setStorageSync('token_timestamp', Date.now());
  Taro.setStorageSync('refresh_token', tokenData.refresh_token);
}

// 重新抓取token
export function tryRefreshToken() {
  return Taro.getStorageSync('access_token');
}

// login
export async function login({username, password}) {
  const loginData = {
    client_id: 'aers',
    username,
    password,
    grant_type: 'password',
  };
  const res = await Taro.request('/auth/realms/aers/protocol/openid-connect/token', {method: 'post', loginData});
  const {data, statusCode = ''} = res;
  if (statusCode && statusCode === 200) {
    saveTokenInfo(data);
    return data;
  }
  return false;
}
export function friendlyFormatTime(stringTime) {
  //将字符串转换成时间格式
  let timePublish = new Date(stringTime);
  let timeNow = new Date();
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let month = day * 30;
  let year = month * 12;
  let diffValue = timeNow - timePublish;
  let diffMonth = diffValue / month;
  let diffWeek = diffValue / (7 * day);
  let diffDay = diffValue / day;
  let diffHour = diffValue / hour;
  let diffMinute = diffValue / minute;
  let diffYear = diffValue / year;
  let result = null;
  if (diffValue < 0) {
    result = "刚刚";
  } else if (diffYear > 1) {
    result = parseInt(diffYear) + "年前";
  } else if (diffMonth > 1) {
    result = parseInt(diffMonth) + "月前";
  } else if (diffDay > 1) {
    result = parseInt(diffDay) + "天前";
  } else if (diffHour > 1) {
    result = parseInt(diffHour) + "小时前";
  } else if (diffMinute > 1) {
    result = parseInt(diffMinute) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
};

export function authLocation (fun) {
  Taro.getLocation({
    type: "wgs84",
    success(res) {
      console.log('获取定位', res);
      Taro.setStorageSync(
        "currentLocation",
        JSON.stringify(res)
      );
      Taro.setStorageSync(
        "chooseLocation",
        JSON.stringify(res)
      );
      // const newDk = new QQMapWX({
      //   key: qqMapKey,
      // });
      // newDk.reverseGeocoder({
      //   //使用腾讯位置服务的API传入经纬度
      //   location: {
      //     latitude: res?.latitude,
      //     longitude: res?.longitude,
      //   },
      //   success: function (res) {
      //     const { result = {} } = res;
      //     const temLocation = {
      //       name: result?.formatted_addresses?.recommend || "",
      //       address: result?.address || "",
      //       latitude: result?.location?.lat,
      //       longitude: result?.location?.lng,
      //     };
      //     // Taro.showToast({
      //     //   title: '授权成功',
      //     //   icon: 'none'
      //     //   // duration: 2000
      //     // })
      //     // wx.openLocation({
      //     //   latitude:result?.location?.lat,	//维度
      //     //   longitude: result?.location?.lng, //经度
      //     //   name: result?.formatted_addresses?.recommend || "",	//目的地定位名称
      //     //   scale: 15,	//缩放比例
      //     //   address: result?.address || ""	//导航详细地址
      //     // });
      //     Taro.setStorageSync(
      //       "currentLocation",
      //       JSON.stringify(temLocation)
      //     );
      //     Taro.setStorageSync(
      //       "chooseLocation",
      //       JSON.stringify(temLocation)
      //     );
      //     fun(temLocation);
      //   },
      //   fail: (res) => {
      //     console.log('失败的res2', res)
      //   }
      // });
    },
    fail: (res) => {
      Taro.getSetting({
        success: (res) => {
          var statu = res.authSetting;
          if (!statu["scope.userLocation"]) {
            //没授权
            Taro.showModal({
              title: "获取不到您的定位",
              content:
                "允许“金冠智充程序”使用您的定位,用于推荐就近的充电场站",
              confirmColor: "#237AF5",
              confirmText: "开启定位",
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting({
                    success: (data) => {
                      if (
                        data.authSetting["scope.userLocation"]
                      ) {
                        // 调用地图
                        // wx.chooseLocation({
                        //   success: function (res) {
                        //     Taro.setStorageSync(
                        //       "currentLocation",
                        //       JSON.stringify(res)
                        //     );
                        //     wx.navigateTo({
                        //       url: "/pages/hospitals/index",
                        //     });
                        //   },
                        // });
                        const newDk = new QQMapWX({
                          key: qqMapKey,
                        });
                        newDk.reverseGeocoder({
                          //使用腾讯位置服务的API传入经纬度
                          location: {
                            latitude: res?.latitude,
                            longitude: res?.longitude,
                          },
                          success: function (res) {
                            const { result = {} } = res;
                            const temLocation = {
                              name:
                                result?.formatted_addresses
                                  ?.recommend || "",
                              address: result?.address || "",
                              latitude: result?.location?.lat,
                              longitude: result?.location?.lng,
                            };
                            Taro.setStorageSync(
                              "currentLocation",
                              JSON.stringify(temLocation)
                            );
                          },
                        });
                      }
                    },
                    fail: () => {
                      // wx.redirectTo({
                      //   url: `/pages/index/index`,
                      // });
                    },
                  });
                } else {
                  // wx.redirectTo({
                  //   url: `/pages/index/index`,
                  // });
                }
              },
            });
          } else {
            //已授权
            // wx.chooseLocation({
            //   success: function (res) {
            //     Taro.setStorageSync(
            //       "currentLocation",
            //       JSON.stringify(res)
            //     );
            //   },
            // });
          }
        },
      });
    },
  });
}
export function getUserProfile (phoneObj) {
  const openid = Taro.getStorageSync('openid') || '';
  const session_key = Taro.getStorageSync('session_key') || '';
  const accessToken = tryRefreshToken();
  Taro.getUserInfo({
    desc: "用于微信账号与平台账号绑定", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      const {iv = '', encryptedData = ''} = res;
      Taro.setStorageSync("userInfoStr", JSON.stringify(res));
      if (res && iv && openid && session_key){
        Taro.request({
          url: `${base}/mini/wxLogin`,
          data: {
            encryptedData,
            iv,
            openid,
            sessionKey: session_key
          },
          header: {
            "content-type": "application/json",
            "appid": 'wx52f6aba688ce70f6',
            "Authorization": accessToken ? "Bearer " + accessToken : '',
          },
          method: "POST",
        }).then((res) => {
          const { data: {data = {}, code, errmsg = ''} = {} } = res;
        });
      }
    },
    fail: (res) => {
      console.log('警告,不授权了', res);
      //用户按了拒绝按钮
      // wx.showModal({
      //   title: "警告",
      //   content: "您点击了拒绝授权，部分功能将无法使用，请授权之后重试!!!",
      //   showCancel: false,
      //   confirmText: "返回",
      //   success: function (res) {
      //     // 用户没有授权成功，不需要改变 isHide 的值
      //     if (res.confirm) {
      //       console.log("用户点击了“返回授权”");
      //     }
      //   },
      // });
    },
  });
};

export function wxLogin(){
  Taro.login({
    success(res) {
      console.log('登录成功', res);
      const accessToken = tryRefreshToken();
      if (res.code) {
        //发起网络请求
        // 获取到用户登录凭证
        Taro.request({
          url: `${base}/mini/wxLoginPre`,
          data: res.code,
          header: {
            "content-type": "application/json",
            "appid": 'wx52f6aba688ce70f6',
            "Authorization": accessToken ? "Bearer " + accessToken : '',
          },
          method: "POST",
        }).then(( res) => {
          const { data: {data = {}, code, errmsg = ''} = {} } = res;
          console.log('换取token成功RES', res)
          const {
            openId = "",
            sessionKey = "",
            token = '',
            // registerFlag = 1,
            // phoneNumber = '',
          } = data;
          if (openId) {
            Taro.setStorageSync("openid", openId);
            Taro.setStorageSync("session_key", sessionKey);
            Taro.setStorageSync('access_token', token);
            console.log('access_token', token);
            // Taro.setStorageSync("isLogin", registerFlag === 0);
            // Taro.setStorageSync("phoneNumber", phoneNumber);
          } else {
            code !==200 &&
            Taro.showToast({
              title: `openid获取失败.${errmsg}`,
              icon: "none",
              duration: 1500,
            });
          }
        });
      } else {
        Taro.showToast({
          title: `登录失败.${res.errMsg}`,
          icon: "none",
          duration: 1500,
        });
      }
    },
  }).then();
}
export function getRandomFloorNum(max, min){
  return Math.floor(Math.random() * (max-min)) + min;
}
export function getGunStatus(code){
  switch (code) {
    case '0':
      return '离线';
    case '1':
      return '空闲中';
    case '2':
      return '已插枪';
    case '3':
      return '充电中';
    case '4':
      return '异常';
    default:
      return ''
  }
}
